#pragma once

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#include <cstring>
#include <iostream>
#include <string>
#include "log.hpp"

class Client
{
public:
    Client(std::string clientip, uint16_t clientport) : socket_(-1), ip_(clientip), port_(clientport) {}

    void Init()
    {
        socket_ = socket(AF_INET, SOCK_STREAM, 0);
        if (socket_ < 0)
        {
            lg(FATAL, "soket creat error");
            exit(-1);
        }
    }

    void Request()
    {
        while (true)
        {
            // sleep(1);
            sleep(15);
            close(socket_);
            lg(INFO, "client close soket:%d", socket_);
        }
    }

    void Start()
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET; // 表示IPv4
        inet_pton(AF_INET, ip_.c_str(), &(server.sin_addr));
        server.sin_port = htons(port_);
        socklen_t len = sizeof(server);

        if (connect(socket_, (sockaddr *)&server, len))
        {
            lg(FATAL, "connect error");
            exit(2);
        }

        Request();
    }

private:
    int socket_;
    std::string ip_;
    uint16_t port_;
};